package cn.hh.wechatkit.api.token;

import cn.hh.wechatkit.exception.Wx_Exception_InvalidJsonParse;
import cn.hh.wechatkit.exception.Wx_Exception_InvalidResponse;
import cn.hh.wechatkit.pojo.token.WxToken_ApiTicketToken;
import cn.hhchat.kit.http.httpUtil;
import com.alibaba.fastjson.JSON;
import okhttp3.Headers;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

import static cn.hh.wechatkit.helper.WxConst.APITicketToken_GET_URL;

/**
 * Created this one by HMH on 2017/5/5.
 */
public class WxAPI_APITicket_Token_Api {

    private static Logger logger = LoggerFactory.getLogger(WxAPI_APITicket_Token_Api.class);

    /**
     * 获取 JS API 的令牌
     * @param ACCESS_TOKEN 基础令牌
     * @return 返回空
     */
    public static WxToken_ApiTicketToken getToken(String ACCESS_TOKEN) throws IOException, Wx_Exception_InvalidResponse, Wx_Exception_InvalidJsonParse {
        String url = APITicketToken_GET_URL.replace("ACCESS_TOKEN", ACCESS_TOKEN);
        Response response = httpUtil.get(url);
        if (response != null) {

            try {
                Headers headers = response.headers();
                String body = response.body().string();
                //解析字符串
                WxToken_ApiTicketToken wxApiTicketToken = JSON.parseObject(body, WxToken_ApiTicketToken.class);
                wxApiTicketToken.setExpires_time(wxApiTicketToken.getExpires_in() * 1000 + headers.getDate("date").getTime() - 1300000);
                return wxApiTicketToken;
            } catch (IOException e) {
                logger.error("处理返回的ApiTicketToken发生错误\n",e);
                throw new Wx_Exception_InvalidJsonParse("处理返回的ApiTicketToken发生错误\n",e);

            }
        }
        throw new Wx_Exception_InvalidResponse("没有收到响应，或者请求出错");
    }
}
